<!DOCTYPE html>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<style>

div {
  position: relative;
  height: 50px;
  width: 50px;
  background-color: blue;
}
.animated {
  animation: 20s linear -10s anim;
}
@keyframes anim {
  from { left: -9500px; }
  to   { left: 10500px; }
}

</style>
<div id="target"></div>
<div id="clock" class="animated"></div>
<script>
'use strict';

var asyncHandle = async_test('Resetting display from "none" causes animation to restart');

window.onload = function() {
  target.addEventListener('animationstart', onStart);
  target.classList.add('animated');
};

function onStart() {
  target.removeEventListener('animationstart', onStart);
  requestAnimationFrame(setDisplayNone);
}

function setDisplayNone() {
  target.style.display = 'none';

  requestAnimationFrame(function() {
    requestAnimationFrame(asyncHandle.step_func(setDisplayBlock));
  });
}

var initialClock;
function setDisplayBlock() {
  assert_equals(target.getAnimations().length, 0);
  target.addEventListener('animationstart', onRestart);
  target.style.display = 'block';
  initialClock = parseFloat(getComputedStyle(clock).left);
  assert_equals(getComputedStyle(target).left, '500px');
}

function onRestart(e) {
  requestAnimationFrame(asyncHandle.step_func_done(measureProgress));
}

function measureProgress() {
  assert_equals(target.getAnimations().length, 1);

  // The animation's progress is based on the time since display: block,
  // not the time since the 'animated' class was first added to target.
  var elapsedTime = parseFloat(getComputedStyle(clock).left) - initialClock;
  assert_approx_equals(parseFloat(getComputedStyle(target).left), 500 + elapsedTime, 1);
}
</script>
